<?php
/**
 * Created by JetBrains PhpStorm.
 * User: xx
 * Date: 14-7-24
 * Time: 下午3:44
 * To change this template use File | Settings | File Templates.
 * 持久化模型
 */

class persistence_model extends CI_Model
{
    function __construct()
    {
        parent::__construct();

        /**
         * 对模块的返回值进行扩展
         * 4000-5000 目录模型使用
         */
        $this->return_status[4001] = "";
        $this->return_status[4002] = "";
    }

    public function get_pers_data($code)
    {
        $ret = new Ret($this);
        $rows = $this->get_pers($code);
        if ($rows) {
            $ret->set_code(0);
            //$ret->set_data(unserialize($rows['pers_value']));
            $ret->set_data(json_decode($rows['pers_value'], true));
        }
        return $ret;
    }

    public function persistence($code, $data)
    {
        $prs_tmp = $this->get_pers($code);
        if ($prs_tmp) { //存在edit_pers
            //$prs_tmp['pers_value'] = serialize($data);
            $prs_tmp['pers_value'] = json_encode($data);
            $prs_tmp['update_time'] = time();
            $this->edit_pers($prs_tmp['pers_id'], $prs_tmp);
        } else { //add_pers
            $prs_tmp = array(
                'pers_code' => $code,
                //'pers_value' => serialize($data),
                'pers_value' => json_encode($data),
                'update_time' => time()
            );
            $this->add_pers($prs_tmp);
        }
    }

    /**
     * $row = $query->row_array();
     * @return bool
     */
    private function get_pers($code)
    {
        $rows = FALSE;
        $sql = "SELECT * FROM " . XS_PERSISTENCE . " WHERE pers_code = ?";
        $query = $this->db->query($sql, array($code));
        if ($query->num_rows() > 0) {
            $rows = $query->first_row('array');
        }

        return $rows;
    }

    private function add_pers($data)
    {
        $this->db->insert(XS_PERSISTENCE, $data);
    }

    private function edit_pers($pers_id, $data)
    {
        $this->db->where('pers_id', $pers_id);
        $this->db->update(XS_PERSISTENCE, $data);
    }
}